package com.sl.au.controller;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import com.sl.au.entity.Account;
import com.sl.au.entity.Chance;
import com.sl.au.entity.ChanceStatistics;
import com.sl.au.entity.DateQueryItem;
import com.sl.au.entity.Module;
import com.sl.au.entity.User;
import com.sl.au.service.ChanceService;
import com.sl.au.service.ExcelService;
import com.sl.utils.DataConverter;

@RestController
@RequestMapping(value = "/ui/chanceQuery")
public class ChanceQueryController extends BaseController {

	@Autowired
	ChanceService chanceService;

	@Autowired
	ExcelService excelService;

	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView index() {
		ModelAndView modelAndView = createLayoutView("chanceQuery/chanceQueryindex");
		return modelAndView;
	}

	/**
	 * 销售信息服务器分页数据
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getpage", method = RequestMethod.GET)
	public Map<String, Object> getPage(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, String> condition = new HashMap<String, String>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key = request.getParameter("key");
		Account a = this.getMyAccount();
		Module module = this.getPageModule("chanceQuery");
		String dataFilter = module.getDataFilter();
		User user = a.getUser();
		condition.put("key", key);
		condition.put("dataFilter", dataFilter);
		List<Chance> saleChances = chanceService.getQueryChances(start, length, condition, user, null, null);
		Long count = chanceService.getQueryCount(condition, user);
		map.put("data", saleChances);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}

	/**
	 * 销售信息服务器分页数据HQL组合查询分页
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getpage/hql", method = RequestMethod.GET)
	public Map<String, Object> getPageHql(HttpServletRequest request) {
		Map<String, Object> qMap = new HashMap<String, Object>();
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> condition = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key = request.getParameter("key");
		Account a = this.getMyAccount();
		Module module = this.getPageModule("chanceQuery");
		String dataFilter = module.getDataFilter();
		User user = a.getUser();
		this.getQueryParams(qMap);
		condition.put("key", key);
		condition.put("dataFilter", dataFilter);
		condition.put("qMap", qMap);
		List<Chance> saleChances = chanceService.getQueryChancesHql(start, length, condition, user, "createTime",
				"desc");
		Long count = chanceService.getQueryChancesCountHql(condition, user);
		map.put("data", saleChances);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}

	private void getQueryParams(Map<String, Object> qMap) {
		String names[] = { "isSucceed","name", "chancePriority", "deviceState", "sourcePower", "source", "sourceUnit",
				"projectState","orderUnit", "orderPerson", "orderUnitAddr" ,"creator"};
		for (String name : names)
			if (StringUtils.hasText(request.getParameter(name))) {
				qMap.put(name, request.getParameter(name));
			}
		if(null !=request.getParameter("orderAmount") && request.getParameter("orderAmount")!=""){
			qMap.put("orderAmount",Integer.valueOf(request.getParameter("orderAmount")) );
		}
		if (null != this.getDateQueryItem("createTime"))
			qMap.put("	", this.getDateQueryItem("createTime"));
		System.out.println(qMap.get("  "));

	}

	// 导出选择项
	@RequestMapping(value = "/exportbyselect/{key}", method = RequestMethod.GET)
	@ResponseBody
	public ResponseEntity<Resource> exportSelects(@PathVariable String key, HttpServletRequest request)
			throws UnsupportedEncodingException {
		String id[] = key.split(",");
		List<Chance> saleChances = new ArrayList<Chance>();
		Chance saleChance = new Chance();
		for (int i = 0; i < id.length; i++) {
			saleChance = chanceService.getRepository().findOne(id[i]);
			saleChances.add(saleChance);
		}
		return this.excelService.toExcel(saleChances, "销售信息.xlsx");
	}
	// 导出选择项
	@RequestMapping(value = "/printnumber/{year}", method = RequestMethod.GET)
	@ResponseBody
	public ResponseEntity<Resource> printnumber(@PathVariable Integer year, HttpServletRequest request)
			throws UnsupportedEncodingException {
		Account a = this.getMyAccount();
		User user = a.getUser();
		List<ChanceStatistics> ChanceStatistics = chanceService.getChanceStatistics(year,year+1,user.getSaleArea().getSuperior());
		return this.excelService.toExcel(ChanceStatistics, "个人收集信息统计表.xlsx");
	}

	// 导出搜索所得结果项，关键字为空时，导出全部
	@RequestMapping(value = "/exportbykeyword/{key}", method = RequestMethod.GET)
	public ResponseEntity<org.springframework.core.io.Resource> excelFile(@PathVariable String key,HttpServletRequest request) 
			throws UnsupportedEncodingException {
		Map<String, Object> qMap = new HashMap<String, Object>();
		Map<String, Object> condition = new HashMap<String, Object>();
//		String key = request.getParameter("key");
		Account a = this.getMyAccount();
		Module module = this.getPageModule("chanceQuery");
		String dataFilter = module.getDataFilter();
		User user = a.getUser();
		String searchKeyWord[]=key.split("\\+");
		DateQueryItem d=new DateQueryItem();
		for(int j=1;j<searchKeyWord.length;j=j+2)
		{
			
			if(searchKeyWord[j].equals("createTimeStartDate")){
				d.setStartDate(DataConverter.formatDateYMD(searchKeyWord[j+1]));
			}
			else if(searchKeyWord[j].equals("createTimeEndDate")){
				d.setEndDate(DataConverter.formatDateYMD(searchKeyWord[j+1]));
			}
			else if(searchKeyWord[j].equals("orderAmount")){
				qMap.put(searchKeyWord[j],Integer.valueOf(searchKeyWord[j+1] ));
			}
			else{
			qMap.put(searchKeyWord[j],searchKeyWord[j+1] );
			}
		}
		if(null!=d){
			d.setPropertyName("createTime");				
		}
		qMap.put("	", d);
//		this.getQueryParams(qMap);
		condition.put("key", key);
		condition.put("dataFilter", dataFilter);
		condition.put("qMap", qMap);
		List<Chance> saleChances = chanceService.getQueryChancesHql(0, Integer.MAX_VALUE, condition, user, "createTime",
				"desc");

		return this.excelService.toExcel(saleChances, "销售信息.xlsx");
	}
}
